package com.winter.service.impl;

import com.winter.mapper.OrderInfoMapper;
import com.winter.mapper.ReplyMapper;
import com.winter.mapper.TopicMapper;
import com.winter.mapper.UserMapper;
import com.winter.model.OrderInfo;
import com.winter.model.Reply;
import com.winter.model.Topic;
import com.winter.model.User;
import com.winter.service.ReplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ReplyServiceImpl implements ReplyService {

    //默认3天自动确认
    public static final int TIME = 30000;
    @Autowired
    private OrderInfoMapper mapper;
    @Autowired
    private TopicMapper topicMapper;

    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ReplyMapper replyMapper;

    public long currentTid=0;

    //提交答案
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void answerQuestin(Map<String, Object> paramMap) {

        Date endDate = (Date) paramMap.get("endDate");//提问者设置的截止日期
        Date submitDate = (Date) paramMap.get("submitDate");//枪手提交问题时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String currentDate = sdf.format(new Date());
        //枪手回答的问题
        long gunManId = (long) paramMap.get("GunmanId");//答题的枪手id

        Reply reply = new Reply();
        reply.setrTid(paramMap.containsKey("rtid") ? (long) paramMap.get("rtid") : null);//主帖id
        reply.setrNumber(paramMap.containsKey("rnumber") ? (String) paramMap.get("rnumber") : null);//跟帖id
        reply.setrSid(paramMap.containsKey("rSid") ? (long) paramMap.get("rSid") : null);//板块id
        reply.setrUid(gunManId);//枪手id
        reply.setrTopic(paramMap.containsKey("rTopic") ? (String) paramMap.get("rTopic") : null);//标题
        reply.setrContents(paramMap.containsKey("rContents") ? (String) paramMap.get("rContents") : null);//答案
        reply.setrTime(new Date());
        reply.setCreateDate(new Date());
        reply.setCreateUser("ball");
        reply.setUpdateDate(new Date());
        reply.setUpdateUser("ball");
        replyMapper.insert(reply);
        //找到回答的问题修改状态
        Topic topic = topicMapper.selectByPrimaryKey((long) paramMap.get("rtid"));
        topic.setFlag(3);
        topicMapper.updateByPrimaryKeySelective(topic);

        //提交答案以后判断是否超过截止日期
        /**如果枪手没有按照规定时间提交答案,枪手违约,返还定金,并处50%的资产作为罚金
         * 25%交给用户,25%交于平台
         */
//		long orderNumber = (long) paramMap.get("orderNumber");
        OrderInfo order = orderInfoMapper.selectByTopicId((long) paramMap.get("rtid"));
        long userId = order.getBuyerId();//提问者id金是提问者佣金的20%;

        BigDecimal orderFee = order.getOrderAmount().multiply(new BigDecimal(0.2));//此时返还定
        //判断当前时间是否在订单时间+规定时间内
        if (endDate.before(submitDate)) {//惩罚

            User gunMan = userMapper.selectByPrimaryKey(gunManId);//枪手拥有的资产

            gunMan.setMoney(gunMan.getMoney().subtract(orderFee).subtract(orderFee.multiply(new BigDecimal(0.5))));//罚款
            userMapper.updateByPrimaryKeySelective(gunMan);

            User user = userMapper.selectByPrimaryKey(userId);//提问者拥有的资产
            user.setMoney(user.getMoney().add(orderFee).add(orderFee.multiply(new BigDecimal(0.25))));
            userMapper.updateByPrimaryKeySelective(user);

            User adminUser = userMapper.selectByPrimaryKey(Long.parseLong("3"));//平台
            adminUser.setMoney(adminUser.getMoney().add(orderFee).add(orderFee.multiply(new BigDecimal(0.25))));
            userMapper.updateByPrimaryKeySelective(adminUser);


        } else {//触发自动确认定时任务

//            TimerTask task = new TimerTask() {
//                public void run() {
//                    System.err.println("12312435436456");
            long id =(long)paramMap.get("tid");
            System.err.println(id);
            currentTid = id;//把前台的值放入currentTid
                   autoConfirm();
//                    }
//
//            };
//            Timer t = new Timer();
//            System.err.println("12312435436456");
//            t.schedule(task, TIME);
//            System.err.println("12ASDSFDGFHGH36456");
        }


    }

    //用户确认答案并且付费将订单状态改变
    public void responseAnswer(Map<String, Object> paramMap) {
        //判断是否有中期
        int isMiddle = (int) paramMap.get("isMiddle");

        if (isMiddle == 0) {//有中期
            //如果有中期判断属于哪个状态付款 1中期第一次确认付款  2 中期已经已经验收,枪手打完最后的题目,用户支付尾款 比例2:3:5
            //判断中期订单状态
            byte orderStatus = (byte) paramMap.get("orderStatus");
            if (orderStatus == 2) {//中期已经验收,中期第二次提交,枪手打完最后的题目,用户支付尾款,订单完结
                long tid = (long) paramMap.get("tid");//获得标题id
                String orderNumber = (String) paramMap.get("orderNumber");//获得订单号
                //问题状态便成完结
                Topic topic = topicMapper.selectByPrimaryKey(tid);
                topic.setFlag(4);//完结
                topicMapper.updateByPrimaryKeySelective(topic);
                //订单状态变成已付款
                OrderInfo info = orderInfoMapper.selectByOrderNumber(orderNumber);
                info.setOrderStatus(Byte.parseByte("3"));
                orderInfoMapper.updateByPrimaryKeySelective(info);

                //付费
                BigDecimal fee = topic.getFee();//提问者支付的赏金
                BigDecimal gunManFee = topic.getFee().multiply(new BigDecimal(0.4));//枪手最后获得的尾款等于提问的支付赏金的80%*50%
                long buyId = info.getBuyerId();
                long gunManId = info.getGunmanId();
                User buyer = userMapper.selectByPrimaryKey(buyId);
                buyer.setMoney(buyer.getMoney().subtract(gunManFee));
                userMapper.updateByPrimaryKeySelective(buyer);
                //枪手收钱
                User gunMan = userMapper.selectByPrimaryKey(gunManId);
                buyer.setMoney(buyer.getMoney().add(gunManFee));
                userMapper.updateByPrimaryKeySelective(gunMan);
            } else {//第一次中期验收

                long tid = (long) paramMap.get("tid");//获得标题id
                String orderNumber = (String) paramMap.get("orderNumber");//获得订单号
                //问题状态中期验收
                Topic topic = topicMapper.selectByPrimaryKey(tid);
                topic.setFlag(3);//中期验收
                topicMapper.updateByPrimaryKeySelective(topic);
                //订单状态变成中期已付款
                OrderInfo info = orderInfoMapper.selectByOrderNumber(orderNumber);
                info.setOrderStatus(Byte.parseByte("2"));
                orderInfoMapper.updateByPrimaryKeySelective(info);

                //付费
                BigDecimal fee = topic.getFee();//提问者支付的赏金
                BigDecimal gunManFee = topic.getFee().multiply(new BigDecimal(0.24));//枪手的中期款等于提问的支付赏金的80%*30%
                long buyId = info.getBuyerId();
                long gunManId = info.getGunmanId();
                User buyer = userMapper.selectByPrimaryKey(buyId);
                buyer.setMoney(buyer.getMoney().subtract(gunManFee));
                userMapper.updateByPrimaryKeySelective(buyer);
                //枪手收钱
                User gunMan = userMapper.selectByPrimaryKey(gunManId);
                buyer.setMoney(buyer.getMoney().add(gunManFee));
                userMapper.updateByPrimaryKeySelective(gunMan);

            }

        } else {//没有中期
            long tid = (long) paramMap.get("tid");//获得标题id
            String orderNumber = (String) paramMap.get("orderNumber");//获得订单号
            //问题状态便成完结
            Topic topic = topicMapper.selectByPrimaryKey(tid);
            topic.setFlag(4);//完结
            topicMapper.updateByPrimaryKeySelective(topic);
            //订单状态变成已付款
            OrderInfo info = orderInfoMapper.selectByOrderNumber(orderNumber);
            info.setOrderStatus(Byte.parseByte("3"));
            orderInfoMapper.updateByPrimaryKeySelective(info);

            //付费
            BigDecimal fee = topic.getFee();//提问者支付的赏金
            BigDecimal gunManFee = topic.getFee().multiply(new BigDecimal(0.64));//枪手最后获得的赏金等于提问的支付赏金的80%*(1-20%的定金)
            long buyId = info.getBuyerId();
            long gunManId = info.getGunmanId();
            User buyer = userMapper.selectByPrimaryKey(buyId);
            buyer.setMoney(buyer.getMoney().subtract(gunManFee));
            userMapper.updateByPrimaryKeySelective(buyer);
            //枪手收钱
            User gunMan = userMapper.selectByPrimaryKey(gunManId);
            buyer.setMoney(buyer.getMoney().add(gunManFee));
            userMapper.updateByPrimaryKeySelective(gunMan);
        }

    }

    //用户不满意答案
    @Override
    public void unConfirm(Map<String, Object> paramMap) {

        System.err.println(System.currentTimeMillis());
        //判断是否有中期
        int isMiddle = (int) paramMap.get("isMiddle");

        if (isMiddle == 0) {//有中期
            //如果有中期判断属于哪个状态付款
            //判断中期订单状态
            byte orderStatus = (byte) paramMap.get("orderStatus");
            if (orderStatus == 2) {//中期验收过后,不满意答案
                System.out.println("请联系客服协调");
            } else {//第一次中期验收,不满意答案

                long tid = (long) paramMap.get("tid");//获得标题id
                String orderNumber = (String) paramMap.get("orderNumber");//获得订单号
                //问题状态完结
                Topic topic = topicMapper.selectByPrimaryKey(tid);
                topic.setFlag(4);//完结
                topicMapper.updateByPrimaryKeySelective(topic);
                //订单状态变成完结
                OrderInfo info = orderInfoMapper.selectByOrderNumber(orderNumber);
                info.setOrderStatus(Byte.parseByte("3"));//
                orderInfoMapper.updateByPrimaryKeySelective(info);

                //付费
                BigDecimal fee = topic.getFee();//提问者支付的赏金
                BigDecimal gunManFee = topic.getFee().multiply(new BigDecimal(0.2));//定金
                long buyId = info.getBuyerId();
                long gunManId = info.getGunmanId();
                //提问者收回定金
                User buyer = userMapper.selectByPrimaryKey(buyId);
                buyer.setMoney(buyer.getMoney().add(gunManFee));
                userMapper.updateByPrimaryKeySelective(buyer);
                //枪手返回定金
                User gunMan = userMapper.selectByPrimaryKey(gunManId);
                buyer.setMoney(buyer.getMoney().subtract(gunManFee));
                userMapper.updateByPrimaryKeySelective(gunMan);

            }


        } else {//没有中期
            String orderNumber = (String) paramMap.get("orderNumber");//获得订单号
            //订单状态变成完结
            OrderInfo info = orderInfoMapper.selectByOrderNumber(orderNumber);
            info.setOrderStatus(Byte.parseByte("3"));
            orderInfoMapper.updateByPrimaryKeySelective(info);

            long tid = (long) paramMap.get("tid");//获得标题id
            //问题状态便成完结
            Topic topic = topicMapper.selectByPrimaryKey(tid);
            topic.setFlag(4);//完结
            topicMapper.updateByPrimaryKeySelective(topic);
            BigDecimal fee = topic.getFee();//提问者支付的赏金
            BigDecimal gunManFee = topic.getFee().multiply(new BigDecimal(0.2));//枪手定金返回提问者
            long buyId = info.getBuyerId();
            long gunManId = info.getGunmanId();
            //用户收回定金
            User buyer = userMapper.selectByPrimaryKey(buyId);
            buyer.setMoney(buyer.getMoney().add(gunManFee));
            userMapper.updateByPrimaryKeySelective(buyer);
            //枪手返回定金
            User gunMan = userMapper.selectByPrimaryKey(gunManId);
            buyer.setMoney(buyer.getMoney().subtract(gunManFee));
            userMapper.updateByPrimaryKeySelective(gunMan);


        }

        System.err.println(System.currentTimeMillis());
    }

    //枪手最多接单3次
    @Override
    public String checkGetOrder(Map<String, Object> paramMap) {
        List<OrderInfo> list = orderInfoMapper.selectById((long) paramMap.get("GunmanId"));

        if (list.size() > 3) {
            return "true";
        } else {
            return "false";

        }

    }

    //校验枪手资产是否适合接单
    @Override
    public String checkGetOrderOwnMoney(Map<String, Object> paramMap) {
        //如果枪手违约,可能要承担问题的定金+提问者赏金的50%的罚款
        User gunMan = userMapper.selectByPrimaryKey((long) paramMap.get("GunManId"));//查询枪手的资产
        BigDecimal gunManMoney = gunMan.getMoney();
        Topic topic = topicMapper.selectByPrimaryKey((long) paramMap.get("tid"));
        BigDecimal punishMoney = topic.getFee().multiply(new BigDecimal(0.5)).add(topic.getFee().multiply(new BigDecimal(0.2)));//定金+提问者赏金*20%
        if (gunManMoney.compareTo(punishMoney) > 0) {//如果枪手的资产可以支付罚金
            return "false";
        } else {
            return "true";
        }
    }

    //自动确认
    @Scheduled(fixedRate = 10000)
    public void autoConfirm() {
        OrderInfo orderInfo = orderInfoMapper.selectByTopicId(currentTid);
        long isMiddle = orderInfo.getIsMiddle();
        //判断是否有中期
//        int isMiddle = (int) currentMap.get("isMiddle");

        if (isMiddle == 0) {//有中期
            long tid = currentTid;//获得标题id
            String orderNumber = orderInfoMapper.selectByTopicId(tid).getOrderNumber();//获得订单号;//获得订单号

            //问题状态便成完结
            Topic topic = topicMapper.selectByPrimaryKey(tid);
            topic.setFlag(4);//完结
            topicMapper.updateByPrimaryKeySelective(topic);
            //订单状态变成已付款
            OrderInfo info = orderInfoMapper.selectByOrderNumber(orderNumber);
            info.setOrderStatus(Byte.parseByte("3"));
            orderInfoMapper.updateByPrimaryKeySelective(info);

            //付费
            BigDecimal fee = topic.getFee();//提问者支付的赏金

            BigDecimal gunManFee = topic.getFee().multiply(new BigDecimal(0.4));//枪手最后获得的赏金等于提问的支付赏金的50%*(1-20%的定金)
            long buyId = info.getBuyerId();
            long gunManId = info.getGunmanId();
            User buyer = userMapper.selectByPrimaryKey(buyId);
            buyer.setMoney(buyer.getMoney().subtract(gunManFee));
            userMapper.updateByPrimaryKeySelective(buyer);
            //枪手收钱
            User gunMan = userMapper.selectByPrimaryKey(gunManId);
            buyer.setMoney(buyer.getMoney().add(gunManFee));
            userMapper.updateByPrimaryKeySelective(gunMan);

        } else {//没有中期
//            long tid = (long) currentMap.get("tid");//获得标题id
//            String orderNumber = (String) currentMap.get("orderNumber");//获得订单号
            long tid = currentTid;//获得标题id
            String orderNumber = orderInfoMapper.selectByTopicId(tid).getOrderNumber();//获得订单号
            //问题状态便成完结
            Topic topic = topicMapper.selectByPrimaryKey(tid);
            topic.setFlag(4);//完结
            topicMapper.updateByPrimaryKeySelective(topic);
            //订单状态变成已付款
            OrderInfo info = orderInfoMapper.selectByOrderNumber(orderNumber);
            info.setOrderStatus(Byte.parseByte("3"));
            orderInfoMapper.updateByPrimaryKeySelective(info);

            //付费
            BigDecimal fee = topic.getFee();//提问者支付的赏金
            BigDecimal gunManFee = topic.getFee().multiply(new BigDecimal(0.64));//枪手最后获得的赏金等于提问的支付赏金的80%*(1-20%的定金)
            long buyId = info.getBuyerId();
            long gunManId = info.getGunmanId();
            User buyer = userMapper.selectByPrimaryKey(buyId);
            buyer.setMoney(buyer.getMoney().subtract(gunManFee));
            userMapper.updateByPrimaryKeySelective(buyer);
            //枪手收钱
            User gunMan = userMapper.selectByPrimaryKey(gunManId);
            buyer.setMoney(buyer.getMoney().add(gunManFee));
            userMapper.updateByPrimaryKeySelective(gunMan);
        }

    }


}
